package com.winit.schedule.job.tracker.repository.mysql.type.handler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import com.winit.schedule.core.model.JobID;

@MappedTypes({ JobID.class })
@MappedJdbcTypes({ JdbcType.VARCHAR })
public class JobIDTypeHandler implements TypeHandler<JobID> {

    @Override
    public void setParameter(PreparedStatement ps, int i, JobID jobID, JdbcType jdbcType) throws SQLException {
        ps.setString(i, jobID.getJobId());
    }

    @Override
    public JobID getResult(ResultSet rs, String columnName) throws SQLException {
        String jobId = rs.getString(columnName);
        return string2JobID(jobId);
    }

    @Override
    public JobID getResult(ResultSet rs, int columnIndex) throws SQLException {
        String jobId = rs.getString(columnIndex);
        return string2JobID(jobId);
    }

    @Override
    public JobID getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String jobId = cs.getString(columnIndex);
        return string2JobID(jobId);
    }

    private JobID string2JobID(String jobId) {
        if (null != jobId) {
            return new JobID(jobId);
        }
        return null;
    }

}
